/*
 * Copyright (c) 2022-2022 All rights Reserved.
 */

package com.driving.core;

import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import com.driving.core.exception.DrivingException;
import com.driving.core.util.ConfigReader;
import com.driving.core.util.Constant;
import com.driving.core.util.JsonWebToken;
import com.driving.core.util.MessageType.ExceptionType;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 系统拦截器，拦截页面之外的全部请求
 *
 * @author SAGITTAR
 * @since 2017
 */
@Slf4j
@RequiredArgsConstructor
@Component(value = "drivingCoreInterceptor")
public class DrivingCoreInterceptor implements AsyncHandlerInterceptor {

    private final ConfigReader configReader;

    private static final InheritableThreadLocal<Long> TIME = new InheritableThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        TIME.set(Calendar.getInstance().getTimeInMillis());
        String uri = request.getRequestURI();
        log.info("DrivingCoreInterceptor receive uri: {}", uri);
        if (StringUtils.contains(uri, "test")) {
            return true;
        }
        if (StringUtils.contains(uri, "register") || StringUtils.contains(uri, "login")) {
            return true;
        }
        if (StringUtils.contains(uri, "exercise")) {
            return true;
        }
        if (StringUtils.contains(uri, "video")) {
            return true;
        }
        // 放行密码重置
        if (StringUtils.contains(uri, "password-reset")) {
            return true;
        }
        String token = request.getHeader(Constant.TOKEN);
        if (StringUtils.contains(uri, "validate")) {
            if (StringUtils.isNotBlank(token)) {
                return true;
            }
            throw new DrivingException(configReader.getExceptionMessage(ExceptionType.NOT_LOGIN));
        }
        if (StringUtils.isBlank(token)) {
            throw new DrivingException(configReader.getExceptionMessage(ExceptionType.NOT_LOGIN));
        }
        if (StringUtils.startsWith(uri, "/student") && JsonWebToken.parseStudent(token).isEmpty()) {
            throw new DrivingException(configReader.getExceptionMessage(ExceptionType.NOT_LOGIN));
        }
        if (StringUtils.startsWith(uri, "/coach") && JsonWebToken.parseCoach(token).isEmpty()) {
            throw new DrivingException(configReader.getExceptionMessage(ExceptionType.NOT_LOGIN));
        }
        if (StringUtils.startsWith(uri, "/admin") && JsonWebToken.parseAdmin(token).isEmpty()) {
            throw new DrivingException(configReader.getExceptionMessage(ExceptionType.NOT_LOGIN));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        long execution = Calendar.getInstance().getTimeInMillis() - TIME.get();
        log.info("current thread is {}, execution time is {}", Thread.currentThread(), execution);
    }
}
